package com.et.u1.vm.home;

import android.app.Service;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.MediaController;

import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.et.banner.BannerConfig;
import com.et.banner.Transformer;
import com.et.banner.loader.ImageLoader;
import com.et.core.file.AdvHelperKt;
import com.et.core.file.Advert;
import com.et.u1.R;
import com.et.u1.databinding.FragmentHomeBinding;
import com.et.u1.vm.base.BaseFragment;
import com.et.u1.vm.shop.ShopFragment;


import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

import kotlin.Unit;

public class HomeFragment extends BaseFragment<FragmentHomeBinding, HomeViewModel> {

    private String advertInfo;
    private Timer mTimer;
    private final int[] bubbleRes = {R.mipmap.dian, R.mipmap.ji, R.mipmap.gou, R.mipmap.wu, R.mipmap.a};
    private final AtomicInteger atomicInteger = new AtomicInteger();

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @NotNull
    @Override
    public FragmentHomeBinding provideViewBinding(@NotNull LayoutInflater inflater, @org.jetbrains.annotations.Nullable ViewGroup container, @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return FragmentHomeBinding.inflate(inflater, container, false);
    }

    @NotNull
    @Override
    public HomeViewModel provideViewModel() {
        return new ViewModelProvider(this).get(HomeViewModel.class);
    }

    @Override
    public void initEvent() {
        initAdvert();
        if (binding.heartLayout != null) {
            binding.heartLayout.setOnClickListener(v -> replaceFragment(ShopFragment.newInstance()));
        }
        Advert.getInstance().observer(() -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(this::initAdvert);
            }
            return Unit.INSTANCE;
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        showHome(false);
        initBubble();

    }

    @Override
    public void onPause() {
        super.onPause();
        mTimer.cancel();
    }

    private void initBubble() {
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (atomicInteger.get() == bubbleRes.length) atomicInteger.set(0);
                binding.bg.post(() -> {
                    if (binding.heartLayout != null) {
                        binding.heartLayout.addHeart(bubbleRes[atomicInteger.getAndAdd(1)]);
                    }
                });
            }
        }, 200, 400);
    }


    private void initVideo() throws JSONException {
        JSONObject json = new JSONObject(advertInfo);
        String play_order_video = json.getString("play_order_video");
        List<String> nameList = Arrays.asList(play_order_video.split(";"));
        nameList.remove("");
        List<String> srcList = new ArrayList<>();
        for (String name : nameList) {
            if (AdvHelperKt.getGlobalFileEntityMap().get(name) != null) {
                srcList.add(Objects.requireNonNull(AdvHelperKt.getGlobalFileEntityMap().get(name)).getFilePath());
            }
        }
        if (srcList.isEmpty()) return;
        //设置音量
        setVoiceVolume(json.getInt("volume"));
        AtomicInteger atomicInteger = new AtomicInteger(0);
        //设置视频控制器
        MediaController controller = new MediaController(getContext());
        controller.hide();
        if (binding.videoView != null) {
            binding.videoView.setMediaController(controller);
        }
        //播放完成回调
        binding.videoView.setOnCompletionListener(mp -> {
            atomicInteger.getAndIncrement();
            if (atomicInteger.get() == srcList.size()) {
                atomicInteger.set(0);
            }
            binding.videoView.setVideoPath(srcList.get(atomicInteger.get()));
            binding.videoView.start();
        });
        //设置视频路径
        binding.videoView.setVideoPath(srcList.get(atomicInteger.get()));
        //开始播放视频
        binding.videoView.start();
    }


    public void initBanner() {
        try {
            JSONObject json = new JSONObject(advertInfo);
            String play_order_image = json.getString("play_order_image");
            int play_order_image_time = json.getInt("play_order_image_time") * 1000;
            List<String> nameList = Arrays.asList(play_order_image.split(";"));
            nameList.remove("");
            List<String> srcList = new ArrayList<>();
            for (String name : nameList) {
                if (AdvHelperKt.getGlobalFileEntityMap().get(name) != null) {
                    srcList.add(Objects.requireNonNull(AdvHelperKt.getGlobalFileEntityMap().get(name)).getFilePath());
                }
            }
            if (binding.mBanner != null) {
                binding.mBanner.setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        Glide.with(context).load(path).into(imageView);
                    }
                });
            }
            binding.mBanner.setBannerAnimation(Transformer.RotateDown);
            binding.mBanner.setImages(srcList);
            binding.mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
            binding.mBanner.setDelayTime(play_order_image_time);
            binding.mBanner.start();

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void initAdvert() {
        advertInfo = requireContext().getSharedPreferences("adv_info", Context.MODE_PRIVATE).getString("adv", null);
        if (advertInfo == null || AdvHelperKt.getGlobalFileEntityMap().isEmpty()) return;
        try {
            JSONObject json = new JSONObject(advertInfo);
            String play_order_image = json.getString("play_order_image");
            String play_order_video = json.getString("play_order_video");
            if (!play_order_image.isEmpty() && play_order_video.isEmpty()) {
                if (binding.videoView != null && binding.mBanner != null) {
                    binding.videoView.setVisibility(View.GONE);
                    binding.mBanner.setVisibility(View.VISIBLE);
                    initBanner();
                }
            }
            if (play_order_image.isEmpty() && !play_order_video.isEmpty()) {
                if (binding.videoView != null && binding.mBanner != null) {
                    binding.mBanner.setVisibility(View.GONE);
                    binding.videoView.setVisibility(View.VISIBLE);
                    initVideo();
                }
            }
            if (!play_order_image.isEmpty() && !play_order_video.isEmpty()) {
                if (binding.videoView != null && binding.mBanner != null) {
                    binding.mBanner.setVisibility(View.VISIBLE);
                    binding.videoView.setVisibility(View.VISIBLE);
                    initBanner();
                    initVideo();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (binding.videoView != null && binding.mBanner != null) {
                binding.mBanner.invalidate();
                binding.videoView.invalidate();
            }
        }

    }


    private void setVoiceVolume(float value) {
        try {
            AudioManager audioManager = (AudioManager) requireContext().getSystemService(Service.AUDIO_SERVICE);
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//(最大值是15)
            int flag = value > 0 ? -1 : 1;
            currentVolume += flag * 0.1 * maxVolume;
            // 对currentVolume进行限制
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}